// Selected communities.
var selectedCommunities = new Array();

var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);

// Document ready.
$(document).ready(function() {
	
	// Products labels tooltips.
	$('.product-label').tooltip();
	
	// date pickers.
	$('#inscription_birthdate').datepicker({format: "dd-mm-yyyy"}).on('changedate', function(event) {
		$(this).attr('value', event.target.value);
	});
	
	// Add handler for communities buttons for registration.
	$('.communityToogle').bind('click', function(event) {
		var value = $(this).attr('data-id');	
		var valueInArray = $.inArray(value,selectedCommunities);

		// Case of universe.
		if ($(this).hasClass('communityToogleOnLink')) {	
			// Case select
			if (valueInArray == -1) {

				$(this).parents('.panel').removeClass('panel-default').addClass('panel-primary');
				$(this).html('-').removeClass('label-primary').addClass('label-default');
				selectedCommunities.push(value);
			} else {

				$(this).parents('.panel').removeClass('panel-primary').addClass('panel-default');
				$(this).html('+').removeClass('label-default').addClass('label-primary');
				selectedCommunities.splice(valueInArray, 1);
				
				// Trigger children.
				$(this).parents('.panel').find('button.communityToogle').each(function(item) {
					var childValue = $(this).attr('data-id');
					var childValueInArray = $.inArray(childValue,selectedCommunities);
					
					if (childValueInArray != -1)
						$(this).trigger('click');
				});
			}
		}
		
		// Case of category.
		if ($(this).find('.communityToogleOnButton').size() > 0) {
			// Case select.
			if (valueInArray == -1) {

				$(this).removeClass('btn-default').addClass('btn-primary');
				$(this).find('.communityToogleOnButton').html('-').removeClass('label-primary').addClass('label-default');
				selectedCommunities.push(value);
				
				// Trigger parent.
				var parentValue = $(this).parents('.panel').find('span.communityToogle').attr('data-id');
				var parentValueInArray = $.inArray(parentValue,selectedCommunities);
				
				if (parentValueInArray == -1) {
					$(this).parents('.panel').find('span.communityToogle').trigger('click');
				}
			} else {

				$(this).removeClass('btn-primary').addClass('btn-default');
				$(this).find('.communityToogleOnButton').html('+').removeClass('label-default').addClass('label-primary');
				selectedCommunities.splice(valueInArray, 1);
			}
		}
		
		// Set value of field.
		$('#inscription_preferences').val(selectedCommunities.join(':'));
	});
	
	$('#inscription_submit').popover({'animation': true, 'trigger': 'manual'});

	$('#inscription_submit').blur(function(event) {			
		$(this).popover('hide');
	});	
	
	// Form control.
	$('#user').submit(function(){
		var return_value = true;
		var cu_return_value = true;
		
		// Required fields.
		if ($('#inscription_email').val() == "") {
			$('#inscription_email').parent().addClass('has-error');
			return_value = false;
		}
		
		if ($('#inscription_password').val() == "") {
			$('#inscription_password').parent().addClass('has-error');
			return_value = false;
		}
		
		if ($('#inscription_birthdate').val() == "") {
			$('#inscription_birthdate').parent().addClass('has-error');
			return_value = false;
		}		
		
		if ($('#inscription_name').val() == "") {
			$('#inscription_name').parent().addClass('has-error');
			return_value = false;
		}
		
		if ($('#inscription_firstname').val() == "") {
			$('#inscription_firstname').parent().addClass('has-error');
			return_value = false;
		}
		
		if (!$('#inscription_cu').is(':checked')) {
			cu_return_value = false;
		}
		
		if (!return_value) {
			$('#inscription_submit').popover('destroy');
			$('#inscription_submit').attr('data-content', 'Les champs surlignés en rouge sont nécessaire à la validation de votre inscription');
			$('#inscription_submit').popover({'animation': true, 'trigger': 'manual'});
		} else if (!cu_return_value) {
			$('#inscription_submit').popover('destroy');
			$('#inscription_submit').attr('data-content', 'Veuillez accepter les conditions générales d\'utilisation');
			$('#inscription_submit').popover({'animation': true, 'trigger': 'manual'});
		}		
		
		if (!return_value || !cu_return_value) {
			$('#inscription_submit').popover('show');
			return false;
		}
		
		return true;
		
	});
	
	$('#connexionLogin').keydown(function(event) {
		$('div#connexionPanel').popover('destroy');
	});
	
	// Buy button.
	$('#buyButton').bind('click', function() {
		if (!connectedUser) {
			$('#connexionLogin').focus();
			
			if ($(window).width() > 1300)
				$('div#connexionPanel').popover({'animation': true, content: 'Vous devez être identifié(e)', trigger: 'manual', placement: 'right'}).popover('show');
			else
				window.alert('Vous devez être identifié(e)');
		} else {
			
			if (!$(this).attr('data-download-key')) {	
				var url = "/cultu/product/createdownload/" + $(this).attr('data-product-id');
				$.ajax({
					type: 'GET',
					url: url,
					success: function(result) {
						console.log(result);
						$('#buyButton').attr('data-download-key', result);
						$('#buyButton').attr('href', '/cultu/product/dodownload/' + result);
						$('#buyButton').html('Télécharger').removeClass('btn-danger').addClass('btn-success');
					},
					error: function(xhr, textStatus, thrownError) {
						console.log(thrownError);
					}		
				});
			}
		}
	});
	
	// Buy button.
	$('.downloadButton').bind('click', function() {
	
		if (!$(this).attr('data-download-key')) {	
			var url = "/cultu/product/createdownload/" + $(this).attr('data-product-id');
//			$.ajax({
//				type: 'GET',
//				url: url,
//				success: function(result) {
//					console.log(result);
			var result = "";
					$('#buyButton').attr('data-download-key', result);
					$('#buyButton').attr('href', '/cultu/product/dodownload/' + result);
					$('#buyButton').html('Télécharger').removeClass('btn-danger').addClass('btn-success');
//				},
//				error: function(xhr, textStatus, thrownError) {
//				}		
//			});
		}
	});
	
	// Promotion modal.
	$('#promotionModal').on('show.bs.modal', function (e) {
		if (e.relatedTarget == null) {
			return false;
		}
		$('#inputOfferProduct').val(e.relatedTarget.getAttribute('data-product-id'));
		
		$('#product_placeholder > .col-md-4').first().remove();
		var productId = e.relatedTarget.getAttribute('data-product-id');
		var productString = '#product-' + productId;
		$('#product_placeholder').prepend($(productString).clone().removeClass('col-md-2').addClass('col-md-4'));
		$(this).find('.promotionButton').remove();
		$('.promotion-productTitle').empty().append($(productString).find('.product-label').text());
	});
	
	$("#offerSubmit").on('click', function(event) {
		$.ajax({
			type: 'POST',
			url: '/cultu/product/offer',
			dataType: 'json',
			data: $("#offerForm").serialize(),
			success: function(result) {
				console.log(result);
				$('#promotionModal').modal('hide');
			},
			error: function(xhr, textStatus, thrownError) {
			}		
		});
	});
	
	var checkin = $('#inputOfferBegin').datepicker({
		format: "dd-mm-yyyy",
		onRender: function(date) {
			return date.valueOf() < now.valueOf() ? 'disabled' : '';
		}
	}).on('changeDate', function(ev) {
		if (ev.date.valueOf() > checkout.date.valueOf()) {
			var newDate = new Date(ev.date);
			newDate.setDate(newDate.getDate() + 1);
			checkout.setValue(newDate);
		}
			
		checkin.hide();
		$('#inputOfferEnd').focus();
	}).data('datepicker');
	
	var checkout = $('#inputOfferEnd').datepicker({
		format: "dd-mm-yyyy",
		onRender: function(date) {
		    return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
		  }
	}).on('changeDate', function(ev) {
		checkout.hide();
	}).data('datepicker');
});